import { create } from 'zustand';
import { ServoDTO } from './servoDataStore';

// 1. 定义 ServoDataState 类型
export interface ServoDataState {
  searchResults: Array<{ servo: ServoDTO }>;
  commandOutput: string[];
  isVisible: boolean;
  addSearchResult: (baud: number, servo_id: number, error_code: number) => void;
  addCommandOutput: (data: string) => void;
  clearMessages: () => void;
  clearCommandOutput: () => void;
  handleShow: () => void;
  handleHide: () => void;
  toggleVisibility: () => void;
  addDebugMessage: () => void;
}

export const useServoDataStore = create<ServoDataState>((set, get) => ({
  searchResults: [],
  commandOutput: [],
  isVisible: true,

  addSearchResult: (baud, servo_id, error_code) => {
    const newResult = { servo: { baud, servo_id, error_code } };
    set((state) => ({
      searchResults: [...state.searchResults, newResult]
    }));
  },

  addCommandOutput: (data: string) => {
    set((state) => ({
      commandOutput: [...state.commandOutput, data],
    }));
  },

  clearMessages: () => set({ searchResults: [] }),

  clearCommandOutput: () => set({ commandOutput: [] }),

  handleShow: () => set({ isVisible: true }),

  handleHide: () => set({ isVisible: false }),

  toggleVisibility: () => set((state) => ({ isVisible: !state.isVisible })),

  addDebugMessage: () => {
    get().addSearchResult(9600, 1, 0);
  },
}));
